package com.gy.service.impl;

import com.aaa.entity.OrderBackfee;
import com.aaa.entity.OrderBackfeeItem;
import com.aaa.entity.OrderCharge;
import com.aaa.entity.OrderChargeItem;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.gy.mapper.*;
import com.gy.service.CarHistoryBackFeeService;
import com.gy.util.HttpClient;
import com.gy.vo.OrderChargeDtoListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Author GaoYa
 * @Date 2023/4/2 15:43
 * @Version 1.5
 */
@Service
public class CarHistoryBackFeeServiceImpl implements CarHistoryBackFeeService {
    @Autowired(required = false)
    private OrderBackFeeMapper buyerFeeDao;

    @Autowired(required = false)
    private CareOrderItemMapper careOrderItemDao;

    @Autowired(required = false)
    private OrderBackfeeltemMapper orderItemDao;

    @Autowired(required = false)
    private OrderChargeItemMapper orderChargeItemDao;

    @Autowired(required = false)
    private OrderChargeMapper orderChargeDao;


    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.mch_id}")
    private String mchId;
    @Value("${weixin.api_key}")
    private String apiKey;

    @Override
    public Result ZFBBackFee(OrderChargeDtoListVo orderChargeDtoListVo) {
        String chId = orderChargeDtoListVo.getOrderChargeDto().getChId();
        BigDecimal orderAmount = orderChargeDtoListVo.getOrderChargeDto().getOrderAmount();
        String patientName = orderChargeDtoListVo.getOrderChargeDto().getPatientName();
        String regId = orderChargeDtoListVo.getOrderChargeDto().getRegId();
        QueryWrapper<OrderCharge> queryWrap = new QueryWrapper<>();
        queryWrap.eq("reg_id", regId);
        List<OrderCharge> orderBackfee = orderChargeDao.selectList(queryWrap);
        for (OrderCharge order : orderBackfee) {
            if (order.getPayType().equals("1")) {
                LocalDateTime createTime = LocalDateTime.now();
                String backId = "ODB";
                Random random = new Random();
                for (int i = 0; i < 19; i++) {
                    backId += String.valueOf(random.nextInt(10));
                }
                buyerFeeDao.insertAllPlus(backId, orderAmount, chId, patientName, regId, createTime);
                List<OrderChargeItem> orderChargeItem = orderChargeDtoListVo.getOrderChargeItemDtoList();
                for (int i = 0; i < orderChargeItem.size(); i++) {
                    orderChargeItemDao.updateStatusImt(orderChargeItem.get(i).getItemId());
                }
                for (int i = 0; i < orderChargeItem.size(); i++) {
                    OrderBackfeeItem orderBackfeeItem = new OrderBackfeeItem();
                    orderBackfeeItem.setBackId(backId);
                    orderBackfeeItem.setCoId(backId);
                    orderBackfeeItem.setItemId(orderChargeItem.get(i).getItemId());
                    orderBackfeeItem.setItemNum(orderChargeItem.get(i).getItemNum());
                    orderBackfeeItem.setItemName(orderChargeItem.get(i).getItemName());
                    orderBackfeeItem.setItemPrice(orderChargeItem.get(i).getItemPrice());
                    orderBackfeeItem.setItemType(orderChargeItem.get(i).getItemType());
                    orderBackfeeItem.setItemAmount(orderChargeItem.get(i).getItemAmount());
                    orderBackfeeItem.setStatus("2");
                    orderItemDao.insert(orderBackfeeItem);
                }
                return new Result(2000, "微信退费成功");
            }
            return new Result(5000, "当前订单不支持现金退费");
        }
      return null;
    }


    @Override
    public Result ZFBOrder(OrderChargeDtoListVo orderChargeDtoListVo) {
        // 根据前来传过来的参数获取患者名称
        String patientName = orderChargeDtoListVo.getOrderChargeDto().getPatientName();
        //生成OrderId；
        String orderId = "ODC";
        Random random = new Random();
        for (int i = 0; i < 19; i++) {
            orderId += String.valueOf(random.nextInt(10));
        }
        //获取总金额
        BigDecimal orderAmount = orderChargeDtoListVo.getOrderChargeDto().getOrderAmount();
        try {
            // 设置请求的参数
            HashMap<String, String> map = new HashMap<>();
            map.put("appid", appId);
            map.put("mch_id", mchId);
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("body", patientName);
            map.put("out_trade_no", orderId);
            //支付金额设置成0.01，毕竟钱不是大风刮来的
            map.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue() + "");
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("notify_url", "http:localhost:8080/charge/docharge");
            map.put("trade_type", "NATIVE");
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setHttps(true);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(map, apiKey));
            httpClient.post();
            // 获取请求的响应结果
            String content = httpClient.getContent();
            //装换为map格式
            Map<String, String> stringMap = WXPayUtil.xmlToMap(content);
            if (stringMap.get("result_code").equals("SUCCESS")) {
                Map<String, Object> result = new HashMap<>();
                result.put("codeUrl", stringMap.get("code_url"));
                result.put("price", orderAmount);
                result.put("orderId", orderId);
                // 获取挂单号id
                String regId = orderChargeDtoListVo.getOrderChargeDto().getRegId();
                //创建时间
                LocalDateTime now = LocalDateTime.now();
                orderChargeDao.insertZFB(orderId, regId, patientName, orderAmount, now);
                List<OrderChargeItem> orderChargeItem = orderChargeDtoListVo.getOrderChargeItemDtoList();
                for (int i = 0; i < orderChargeItem.size(); i++) {
                    careOrderItemDao.updateZFB(orderChargeItem.get(i).getItemId());
                }
                for (int i = 0; i < orderChargeItem.size(); i++) {
                    OrderChargeItem orderChargeItemDto = new OrderChargeItem();
                    orderChargeItemDto.setOrderId(orderId);
                    orderChargeItemDto.setItemId(orderChargeItem.get(i).getItemId());
                    orderChargeItemDto.setItemNum(orderChargeItem.get(i).getItemNum());
                    orderChargeItemDto.setItemType(orderChargeItem.get(i).getItemType());
                    orderChargeItemDto.setStatus("0");
                    orderChargeItemDto.setItemName(orderChargeItem.get(i).getItemName());
                    orderChargeItemDto.setCoId(orderChargeItem.get(i).getCoId());
                    orderChargeItemDto.setItemPrice(orderChargeItem.get(i).getItemPrice());
                    orderChargeItemDto.setItemAmount(orderChargeItem.get(i).getItemAmount());
                    orderChargeItemDao.insert(orderChargeItemDto);
                }
                return new Result(2000, "生成二维码成功", result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(2000, "订单失效了", null);
    }

    @Override
    public Result queryDataAll(String orderId) {
        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            HashMap<String, String> map = new HashMap<>();
            map.put("appid", appId);
            map.put("mch_id", mchId);
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("out_trade_no", orderId);
            httpClient.setHttps(true);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(map, apiKey));
            httpClient.post();
            // 获取请求的响应结果
            String content = httpClient.getContent();
            Map<String, String> StringMap = WXPayUtil.xmlToMap(content);
            if (StringMap.get("trade_state").equals("SUCCESS")) { //二维码支付成功 开始修改订单
                QueryWrapper<OrderChargeItem> wrapper = new QueryWrapper<>();
                wrapper.eq("order_id", orderId);
                List<OrderChargeItem> orderChargeItems = orderChargeItemDao.selectList(wrapper);
                for (int i = 0; i < orderChargeItems.size(); i++) {
                    orderChargeItemDao.updataBystatus(orderId);
                }
                return new Result(2000, "支付成功", true);
            }
        } catch (Exception e) {
        }
        return new Result(2000, "请从新扫描二维码支付", false);
    }


}
